﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace GFluentCode.Tools
{
    public class XmlHelper
    {
        #region 对象-XML

        /// <summary>
        /// Xml读取为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T Read<T>(string filePath) where T : class, new()
        {
            if (!File.Exists(filePath)) return null;

            var xml = XElement.Load(filePath);

            var node = xml.Element(typeof(T).Name);

            var props = typeof(T).GetProperties();

            var item = new T();

            foreach (var prop in props)
            {
                var value = node.Element(prop.Name).Value;
                prop.SetValue(item,
                    ChangeType(value, Type.GetType(prop.PropertyType.FullName)),
                    null);
            }

            return item;
        }        

        /// <summary>
        /// 对象保存为xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="root"></param>
        /// <param name="obj"></param>
        public static void Save<T>(string filePath, string root, T obj) where T : class, new()
        {
            //文件路径检测
            if (!File.Exists(filePath))
            {
                var dir = Path.GetDirectoryName(filePath);

                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            }

            var xml = new XElement(root);
            var node = new XElement(typeof(T).Name);
            xml.Add(node);

            var props = typeof(T).GetProperties();

            foreach (var prop in props)
            {
                var ele = new XElement(prop.Name, prop.GetValue(obj, null));
                node.Add(ele);
            }

            xml.Save(filePath);
        }

        #endregion

        #region 对象List-XML

        /// <summary>
        /// xml读取为list对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="elePath"></param>
        /// <returns></returns>
        public static IList<T> ReadList<T>(string filePath,string  elePath)where T:class,new ()
        {
            if (!File.Exists(filePath)) return null;

            var xml = XElement.Load(filePath);

            if (xml == null) return null;

            var node = xml.Element(elePath);

            if (node == null) return null;

            var props = typeof(T).GetProperties();

            var eleName = typeof(T).Name;

            var list = new List<T>();

            foreach (var ele  in node.Elements(eleName))
            {
                var item = new T();

                foreach(var prop in props)
                {
                    var value = ele.Attribute(prop.Name).Value;
                    prop.SetValue(item,
                        ChangeType(value, Type.GetType(prop.PropertyType.FullName)),
                        null);
                }

                list.Add(item);
            }

            return list;
        }

        /// <summary>
        /// 将List对象写为xml(覆盖)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath">文件路径</param>
        /// <param name="root">根节点，也就是xml根节点名</param>
        /// <param name="elePath">层级节点</param>        
        /// <param name="list"></param>
        public static void Save<T>(string filePath, string root, string elePath, List<T> list) where T : class, new()
        {
            //文件路径检测
            if (!File.Exists(filePath))
            {
                var dir = Path.GetDirectoryName(filePath);

                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            }

            var xml = new XElement(root);
            var node = new XElement(elePath);
            xml.Add(node);

            var props = typeof(T).GetProperties();

            foreach (var obj in list)
            {
                var ele = new XElement(typeof(T).Name);
                foreach (var prop in props)
                {
                    ele.SetAttributeValue(prop.Name, prop.GetValue(obj, null));
                }
                node.Add(ele);
            }

            xml.Save(filePath);
        }
        #endregion

        static object ChangeType(object value, Type type)
        {
            if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
            if (value == null) return null;
            if (type == null) return null;
            if (type == value.GetType()) return value;
            if (type.IsEnum)
            {
                if (value is string)
                    return Enum.Parse(type, value as string);
                else
                    return Enum.ToObject(type, value);
            }
            if (!type.IsInterface && type.IsGenericType)
            {
                Type innerType = type.GetGenericArguments()[0];
                object innerValue = ChangeType(value, innerType);
                return Activator.CreateInstance(type, new object[] { innerValue });
            }
            if (value is string && type == typeof(Guid)) return new Guid(value as string);
            if (value is string && type == typeof(Version)) return new Version(value as string);
            if (!(value is IConvertible)) return value;
            return Convert.ChangeType(value, type);
        }
    }
}
